package com.test.io;

import java.io.RandomAccessFile;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;

public class ChanelDemo {
    public static void main(String[] args) throws  Exception{
        RandomAccessFile afile = new RandomAccessFile("data/nio-data.txt","rw");
        FileChannel inChannel = afile.getChannel();
        ByteBuffer buf = ByteBuffer.allocate(1024);
        //read into buffer
        int byteRead=inChannel.read(buf);
        while (byteRead != -1){
            System.out.println("Read : "+byteRead);
            //将buffer从写模式切换至读模式
            buf.flip();
            while (buf.hasRemaining()){
                System.out.println(buf.get());
            }
            //make buffer ready for writing
            buf.clear();
            byteRead = inChannel.read(buf);
        }
        afile.close();
    }

    public  static void transChannel() throws  Exception{
        RandomAccessFile formFile = new RandomAccessFile("data/fromData.txt","rw");
        RandomAccessFile toFile = new RandomAccessFile("data/toData.txt","rw");

        FileChannel fromChannel=formFile.getChannel();
        FileChannel toChannel=toFile.getChannel();

        toChannel.transferFrom(fromChannel,0,fromChannel.size());
        fromChannel.transferTo(0,fromChannel.size(),toChannel);

    }

    public static void selectorTest() throws Exception{
        Selector selector=Selector.open();
        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.socket().bind(new InetSocketAddress(9999));
        ssc.configureBlocking(false);
        SelectionKey key=ssc.register(selector,SelectionKey.OP_READ);
        while(true){
            int readyChnnel = selector.select();
            if(readyChnnel == 0){
                continue;
            }
            Set<SelectionKey> selectedKeys=selector.selectedKeys();
            Iterator keyIterator = selectedKeys.iterator();
            while (keyIterator.hasNext()){
                SelectionKey key1 = (SelectionKey) keyIterator.next();
                if(key1.isAcceptable()){
                    System.out.println("a connection was accepted by a ServerSocketChannel");
                }else if(key1.isConnectable()){
                    System.out.println("a connection was established with a remote server");
                }else if(key1.isReadable()){
                    System.out.println("a channel is ready for reading");
                }else if(key1.isWritable()){
                    System.out.println("a channel is ready for writing");
                }
                keyIterator.remove();
            }
        }
    }
}
